<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增员工</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                员工编码:
              </span>
              <el-tag
                :type="
                  form.joinPositionStatus == 3
                    ? 'danger'
                    : form.joinPositionStatus == 2
                    ? 'warning'
                    : ''
                "
                >{{ form.code }}</el-tag
              >
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="姓名" prop="name">
                    <el-input
                      v-model="form.name"
                      placeholder="请输入姓名"
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="民族" prop="nation">
                    <el-select
                      style="width: 100%"
                      v-model="form.nation"
                      placeholder="请选择民族"
                    >
                      <el-option
                        v-for="item in mes_user_nation"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性别" prop="sex">
                    <el-select
                      style="width: 100%"
                      v-model="form.sex"
                      placeholder="请选择性别"
                    >
                      <el-option value="1" label="男"></el-option>
                      <el-option value="2" label="女"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="在职状态" prop="joinPositionStatus">
                    <el-select
                      style="width: 100%"
                      v-model="form.joinPositionStatus"
                      placeholder="请选择在职状态"
                    >
                      <el-option
                        v-for="item in mes_user_position_status"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出生日期" prop="birthTime">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.birthTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="政治面貌" prop="political">
                    <el-select
                      style="width: 100%"
                      v-model="form.political"
                      placeholder="请选择政治面貌"
                    >
                      <el-option
                        v-for="item in mes_user_political"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="籍贯" prop="nativePlace">
                    <el-input
                      v-model="form.nativePlace"
                      placeholder="请输入籍贯"
                      maxlength="30"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="身份证号" prop="idCard">
                    <el-input
                      v-model="form.idCard"
                      placeholder="请输入身份证号"
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系电话" prop="telephone">
                    <el-input
                      v-model="form.telephone"
                      placeholder="请输入联系电话"
                      maxlength="30"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="最高学历" prop="maxXl">
                    <el-select
                      style="width: 100%"
                      v-model="form.maxXl"
                      placeholder="请选择最高学历"
                    >
                      <el-option
                        v-for="item in mes_user_max_xl"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="毕业院校" prop="graduationSchool">
                    <el-input
                      v-model="form.graduationSchool"
                      placeholder="请输入毕业院校"
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所学专业" prop="profession">
                    <el-input
                      v-model="form.profession"
                      placeholder="请输入所学专业"
                      maxlength="30"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="所属车间" prop="shworkshop">
                    <!--                                        <el-input v-model="form.deptOne" placeholder="请选择一级部门" maxlength="30" />-->
                    <el-select
                      style="width: 100%"
                      v-model="form.shworkshop"
                      placeholder="请选择所属车间"
                    >
                      <el-option
                        v-for="item in sh_workshop"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="二级部门" prop="deptTwo">
                    <el-input
                      v-model="form.deptTwo"
                      placeholder="请选择二级部门"
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="入职日期" prop="joinTime">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.joinTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="在职岗位" prop="joinPositionPost">
                    <el-input
                      v-model="form.joinPositionPost"
                      placeholder="请输入在职岗位"
                      maxlength="30"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label="照片上传" class="upload-box">
                  <el-upload
                    :class="{ disabled: uploadDisabled }"
                    :limit="1"
                    :multiple="false"
                    :auto-upload="false"
                    :show-file-list="true"
                    :on-change="changePictureUpload"
                    v-model:file-list="fileList"
                    list-type="picture-card"
                    :accept="acceptedFileTypes"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                  >
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="数字签名" class="upload-Signature">
                  <el-upload
                    :class="{ disabledSignature: uploadDisabledSignature }"
                    :limit="1"
                    :multiple="false"
                    :auto-upload="false"
                    :show-file-list="true"
                    :on-change="changePictureUploadSignature"
                    v-model:file-list="fileListSignature"
                    list-type="picture-card"
                    :accept="acceptedFileTypes"
                    :on-preview="handlePictureCardPreviewSignature"
                    :on-remove="handleRemoveSignature"
                  >
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script setup>
import useTagsViewStore from "@/store/modules/tagsView";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getMesUserInfo,
  addMesUserInfo,
  editMesUserInfo,
  addOrEditMesFile,
} from "@/api/basicInfo/personnel";
import { preview } from "vue3-preview-image";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  mes_user_nation,
  mes_user_position_status,
  mes_user_political,
  mes_user_max_xl,
  sh_workshop,
} = proxy.useDict(
  "mes_user_nation",
  "mes_user_position_status",
  "mes_user_political",
  "mes_user_max_xl",
  "sh_workshop"
);
const route = useRoute();
const router = useRouter();
const activeNames = ["1"];
const fileList = ref([]);
const fileListSignature = ref([]);
const userRef = ref(null);
const flag = ref(false);
const acceptedFileTypes = ref("image/*");
const data = reactive({
  form: {},
  rules: {
    // socialCreditCode: [{ required: true, message: "统一社会信用代码不能为空", trigger: "blur" },
    // {
    //     validator: (rule, value, callback) => {
    //         // getProducer({ socialCreditCode: value }).then(res => {
    //         //     if (!route.query.id) {
    //         //         if (res.rows.length > 0) {
    //         //             callback(new Error('统一社会信用代码不能重复'))
    //         //         } else {
    //         //             callback()
    //         //         }
    //         //     } else {
    //         //         callback()
    //         //     }
    //         // })
    //     },
    //     trigger: 'blur'
    // },
    // ],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    nation: [
      { required: true, message: "民族不能为空", trigger: ["blur", "change"] },
    ],
    sex: [
      { required: true, message: "性别不能为空", trigger: ["blur", "change"] },
    ],
    joinPositionStatus: [
      {
        required: true,
        message: "在职状态不能为空",
        trigger: ["blur", "change"],
      },
    ],
    birthTime: [
      {
        required: true,
        message: "出生日期不能为空",
        trigger: ["blur", "change"],
      },
    ],
    political: [
      { required: true, message: "政治面貌不能为空", trigger: "blur" },
    ],
    nativePlace: [{ required: true, message: "籍贯不能为空", trigger: "blur" }],
    idCard: [
      { required: true, message: "身份证号不能为空", trigger: "blur" },
      {
        pattern:
          /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9xX]$/,
        message: "请输入正确的身份证号码",
        trigger: ["blur"],
      },
    ],
    telephone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    maxXl: [
      {
        required: true,
        message: "最高学历不能为空",
        trigger: ["blur", "change"],
      },
    ],
    joinTime: [
      { required: true, message: "入职日期不能为空", trigger: "blur" },
    ],
  },
});

const { form, rules } = toRefs(data);

watch(
  () => route,
  (newValue, oldValue) => {
    if (newValue.query?.id) {
      getMesUserInfo({ id: newValue.query.id }).then((res) => {
        Object.assign(form.value, { ...res.rows[0] });
        form.value.nation = form.value.nation.toString();
        form.value.shworkshop = form.value.shworkshop.toString();

        form.value.joinPositionStatus =
          form.value.joinPositionStatus.toString();
        form.value.political = form.value.political.toString();
        form.value.maxXl = form.value.maxXl.toString();
        if (newValue.query.info) {
          flag.value = true;
        }
        if (res.rows[0].photo) {
          uploadDisabled.value = true;
          fileList.value.push({
            url: import.meta.env.VITE_APP_BASE_API + res.rows[0].photo,
          });
        }
        if (res.rows[0].signature) {
          uploadDisabledSignature.value = true;
          fileListSignature.value.push({
            url: import.meta.env.VITE_APP_BASE_API + res.rows[0].signature,
          });
        }
      });
    }
  },
  { immediate: true }
);
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
};

// 图片上传
const uploadDisabled = ref(false);
const changePictureUpload = (file) => {
  uploadDisabled.value = file?.url ? true : false;
};
const handleRemove = (uploadFile, uploadFiles) => {
  uploadDisabled.value = fileList.value.length >= 1;
};
const handlePictureCardPreview = (uploadFile, uploadFiles) => {
  preview(uploadFile.url);
};
// 签名上传
const uploadDisabledSignature = ref(false);
const changePictureUploadSignature = (file) => {
  uploadDisabledSignature.value = file?.url ? true : false;
};
const handleRemoveSignature = (uploadFile, uploadFiles) => {
  uploadDisabledSignature.value = fileListSignature.value.length >= 1;
};
const handlePictureCardPreviewSignature = (uploadFile, uploadFiles) => {
  preview(uploadFile.url);
};

// 上传图片
const uploadFile = (fileList, fileType, id) => {
  if (fileList.value[0].raw) {
    const formData = new FormData();
    formData.append("foreignKey", id);
    formData.append("fileType", fileType);
    formData.append("file", fileList.value[0].raw);
    addOrEditMesFile(formData).then((res) => {
      // 处理上传成功后的逻辑
    });
  }
};
// 确认
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      if (route.query.id) {
        editMesUserInfo(form.value).then((res) => {
          fileList.value.length > 0 && uploadFile(fileList, 1, route.query.id);
          fileListSignature.value.length > 0 &&
            uploadFile(fileListSignature, 2, route.query.id);
          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          goBack();
        });
      } else {
        addMesUserInfo(form.value).then((res) => {
          fileList.value.length > 0 && uploadFile(fileList, 1, res.data.id);
          fileListSignature.value.length > 0 &&
            uploadFile(fileListSignature, 2, res.data.id);
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          goBack();
        });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-box .disabled :deep(.el-upload--picture-card) {
  display: none;
}

.upload-Signature .disabledSignature :deep(.el-upload--picture-card) {
  display: none;
}
</style>